# app/api/v1/family/pet.py
import logging
from typing import Optional

from fastapi import APIRouter, Body, Query, Path,Depends
from tortoise.expressions import Q

from app.controllers.family.pet import pet_controller
from app.schemas.family.pet import *
from app.utils.request import RequestHandler
from app.utils.app_log import logger
from app.core.auth import get_current_user_required,get_current_superuser
from app.schemas.base.login import JWTPayload

router = APIRouter()

@router.get("/list", summary="获取宠物列表")
async def get_pets(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    name: Optional[str] = Query(None, description="宠物姓名，用于搜索"),
    type: Optional[str] = Query(None, description="宠物类型"),
    health_status: Optional[str] = Query(None, description="健康状态"),
    current_user: JWTPayload = Depends(get_current_superuser)   ## 限制管理员使用
):
    """获取宠物列表"""
    try:
        q = Q()
        if name:
            q &= Q(name__contains=name)
        if type:
            q &= Q(type=type)
        if health_status:
            q &= Q(health_status=health_status)

        total, data = await pet_controller.pet_list(page=page, page_size=page_size, q=q)
        return RequestHandler.success_paginated(data=data, total=total, page=page, page_size=page_size)
    except Exception as e:
        logger.error(f"获取宠物列表失败: {str(e)}")
        return RequestHandler.server_error(message="获取宠物列表失败")

@router.get("/user-pet/list", summary="获取宠物列表")
async def get_pets(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    name: Optional[str] = Query(None, description="宠物姓名，用于搜索"),
    type: Optional[str] = Query(None, description="宠物类型"),
    health_status: Optional[str] = Query(None, description="健康状态"),
    current_user: JWTPayload = Depends(get_current_user_required)   ## 限制管理员使用
):
    """获取一个家庭宠物列表"""  ## 注意需要多返回一个值 监控视频流地址
    try:
        q = Q(family_id = current_user.family_id)
        if name:
            q &= Q(name__contains=name)
        if type:
            q &= Q(type=type)
        if health_status:
            q &= Q(health_status=health_status)

        total, data = await pet_controller.pet_list(page=page, page_size=page_size, q=q)
        return RequestHandler.success_paginated(data=data, total=total, page=page, page_size=page_size)
    except Exception as e:
        logger.error(f"获取宠物列表失败: {str(e)}")
        return RequestHandler.server_error(message="获取宠物列表失败")


@router.get("/{pet_id}", summary="获取宠物详情")
async def get_pet(
    pet_id: int = Path(..., description="宠物ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """获取宠物详情"""
    try:
        pet_info = await pet_controller.get_pet_info(pet_id)
        return RequestHandler.success(data=pet_info)
    except Exception as e:
        logger.error(f"获取宠物详情失败: {str(e)}")
        return RequestHandler.server_error(message="获取宠物详情失败")

@router.delete("/{pet_id}", summary="删除宠物")
async def delete_pet(
    pet_id: int = Path(..., description="宠物ID"),
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """删除宠物"""
    try:
        family_id = current_user.family_id
        delete_result = await pet_controller.remove_pet(pet_id, family_id)
        if delete_result:
            return RequestHandler.success(message="宠物删除成功")
    except Exception as e:
        logger.error(f"删除宠物失败: {str(e)}")
        return RequestHandler.server_error(message="删除宠物失败")

@router.post("/create", summary="创建宠物")
async def create_pet(
    pet_in: PetCreate,
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """创建宠物"""
    try:
        logger.info(f"创建宠物: {pet_in.name}")
        pet_in.user_id = current_user.user_id
        pet_in.family_id = current_user.family_id
        pet = await pet_controller.create_pet(pet_in)
        if pet:
            return RequestHandler.success(message="宠物创建成功", data={"id": pet.id})
    except Exception as e:
        logger.error(f"创建宠物失败: {str(e)}")
        return RequestHandler.server_error(message="创建宠物失败")

@router.put("/{pet_id}", summary="更新宠物")
async def update_pet(
    pet_id: int = Path(..., description="宠物ID"),
    pet_in: PetUpdate = None,
    current_user: JWTPayload = Depends(get_current_user_required)
):
    """更新宠物"""
    try:
        if pet_in:
            pet_in.id = pet_id
        family_id = current_user.family_id
        pet = await pet_controller.update_pet_info(pet_id, pet_in, family_id)
        if pet:
            return RequestHandler.success(message="宠物更新成功")
    except Exception as e:
        logger.error(f"更新宠物失败: {str(e)}")
        return RequestHandler.server_error(message="更新宠物失败")